<script>
import {doGet, doPut} from "../http/httpRequest.js";
import {messageConfirm, messageTip, removeToken} from "../util/util.js";

export default {
  name: "DashboardView",
  computed: {
    menuPermission() {
      return menuPermission
    }
  },

  methods: {
    // 左侧菜单的展开与折叠
    showMenu() {
      this.isCollapse = !this.isCollapse
    },

    // 加载当前登录用户
    loadLoginUser() {
      doGet("/api/login/info", {}).then((resp) => {
        console.log(resp);
        this.user = resp.data.data;
      })
    },

    // 退出登录
    logout() {
      doGet("/api/logout", {}).then(resp => {
        if (resp.data.code == 200) {
          removeToken();
          messageTip("退出成功", "success")
          window.location.href = "/"
        } else {
          messageConfirm("退出异常！是否强制退出？")
              .then(() => {   // 用户点击确定
                // 删除token
                removeToken();
                // 跳转到登录页
                window.location.href = "/"
              })
              .catch(() => {  // 用户点击取消
                messageTip("取消登录！", "warning")
              })
        }
      })
    },

    // 加载当前路由路径
    loadCurrentRouterPath() {
      let path = this.$route.path;
      let arr = path.split("/");
      if (arr.length > 3) {
        this.currentRouterPath = "/" + arr[1] + "/" + arr[2]
      } else {
        this.currentRouterPath = path;
      }
    },

    // 打开用户资料弹窗
    openUserProfile() {
      this.userProfileDialogVisible = true;
    },

    // 打开修改密码弹窗
    openChangePasswordDialog() {
      this.changePasswordDialogVisible = true;
    },

    // 保存新密码
    saveNewPassword() {
      this.$refs.passwordForm.validate((valid) => {
        if (valid) {
          // 添加用户ID
          this.passwordData.userId = this.user.id; // 将当前登录用户的id传递到后端
          if (this.passwordData.newPassword === this.passwordData.confirmPassword) {
            // 发送修改密码请求
            doPut("/api/user/change-password", this.passwordData).then(resp => {
              if (resp.data.code === 200) {
                messageTip("密码修改成功", "success");
                this.changePasswordDialogVisible = false;
              } else {
                messageTip("密码修改失败", "error");
              }
            });
          } else {
            messageTip("两次密码输入不一致", "warning");
          }
        } else {
          messageTip("表单验证失败，请检查输入内容", "warning");
        }
      });
    }
  },

  data() {
    return {
      // 控制左侧菜单的展开与折叠，true为折叠，false为展开
      isCollapse: false,
      // 登录对象,初始值为空
      user: {},
      // 控制仪表盘页面右侧内容体是否显示
      isRounterAlive: true,
      // 当前的路由地址
      currentRouterPath: '',
      // 用户资料弹窗显示状态
      userProfileDialogVisible: false,
      // 修改密码弹窗显示状态
      changePasswordDialogVisible: false,
      // 修改密码的表单数据
      passwordData: {
        userId: '',
        newPassword: '',
        confirmPassword: ''
      },
      // 修改密码的表单验证规则
      passwordRules: {
        newPassword: [
          {required: true, message: '请输入新密码', trigger: 'blur'},
          {min: 6, max: 12, message: '密码长度在6-12位之间', trigger: 'blur'}
        ],
        confirmPassword: [
          {required: true, message: '请确认新密码', trigger: 'blur'}
        ]
      }
    }
  },

  // 提供者（生产者）
  provide() {
    return {
      // 提供给子组件的方法
      reload: () => {
        // 内容隐藏
        this.isRounterAlive = false;
        // 内容重现加载
        this.$nextTick(() => {
          // 当数据更新了，在DOM渲染后自动执行该函数
          this.isRounterAlive = true;
        })
      },
    }
  },

  // vue的生命周期的函数钩子
  mounted() {
    // 加载当前登录用户，该钩子是在渲染后执行
    this.loadLoginUser();
    this.loadCurrentRouterPath();
  },
}
</script>

<template>
  <el-container>
    <!--左部分-->
    <el-aside :width="isCollapse ? '64px' : '200px'">
      <router-link to="/dashboard">
        <div class="menuTitle">营销管理系统</div>
      </router-link>
      <el-menu active-text-color="#ffd04b" background-color="#79bbff" class="el-menu-vertical-demo"
               :default-active="currentRouterPath" text-color="#fff" style="border-right: solid 0px"
               :unique-opened="true"
               :collapse="isCollapse" :collapse-transition="false" :router="true">
        <!--市场活动菜单-->
        <el-sub-menu :index="index" v-for="(menuPermission, index) in user.menuPermissionList" :key="menuPermission.id">
          <template #title>
            <el-icon>
              <component :is="menuPermission.icon"></component>
            </el-icon>
            <span> {{ menuPermission.name }}</span>
          </template>
          <el-menu-item v-for="subPermission in menuPermission.subPermissionList" :key="subPermission.id"
                        :index="subPermission.url"> >
            <el-icon>
              <component :is="subPermission.icon"></component>
            </el-icon>
            {{ subPermission.name }}
          </el-menu-item>
        </el-sub-menu>

      </el-menu>
    </el-aside>

    <!--右部分-->
    <el-container>
      <!--上方-->
      <el-header>
        <el-icon class="show" @click="showMenu">
          <Fold/>
        </el-icon>

        <el-dropdown :hide-on-click="false">
          <span class="el-dropdown-link">
            {{ user.name }}<el-icon class="el-icon--right"><arrow-down/></el-icon>
          </span>
          <template #dropdown>
            <el-dropdown-menu>
              <el-dropdown-item @click="openUserProfile">我的资料</el-dropdown-item>
              <el-dropdown-item @click="openChangePasswordDialog">修改密码</el-dropdown-item>
              <el-dropdown-item divided @click="logout()">退出登录</el-dropdown-item>
            </el-dropdown-menu>
          </template>
        </el-dropdown>

      </el-header>


      <!--中间-->
      <el-main>
        <router-view v-if="isRounterAlive"/>
      </el-main>


      <!--下方-->
      <el-footer>
        独有英雄驱虎豹，更无豪杰怕熊罴！
      </el-footer>
    </el-container>
  </el-container>


  <!-- 用户资料弹窗 -->
  <el-dialog v-model="userProfileDialogVisible" title="我的资料" width="50%" center>
    <el-form :model="user" label-width="120px">
      <el-form-item label="用户名">
        <el-input v-model="user.name" disabled/>
      </el-form-item>
      <el-form-item label="邮箱">
        <el-input v-model="user.email" disabled/>
      </el-form-item>
      <el-form-item label="电话">
        <el-input v-model="user.phone" disabled/>
      </el-form-item>
    </el-form>
    <template #footer>
      <el-button @click="userProfileDialogVisible = false">关闭</el-button>
    </template>
  </el-dialog>

  <!-- 修改密码弹窗 -->
  <el-dialog v-model="changePasswordDialogVisible" title="修改密码" width="50%" center>
    <el-form ref="passwordForm" :model="passwordData" :rules="passwordRules" label-width="120px">
      <el-form-item label="新密码" prop="newPassword">
        <el-input type="password" v-model="passwordData.newPassword" placeholder="请输入新密码"/>
      </el-form-item>
      <el-form-item label="确认密码" prop="confirmPassword">
        <el-input type="password" v-model="passwordData.confirmPassword" placeholder="请确认新密码"/>
      </el-form-item>
    </el-form>
    <template #footer>
      <el-button @click="changePasswordDialogVisible = false">取消</el-button>
      <el-button type="primary" @click="saveNewPassword">确定</el-button>
    </template>
  </el-dialog>

</template>

<style scoped>
.el-aside {
  background-color: #c6e2ff;
}

.el-header {
  background-color: #fde2e2;
  height: 35px;
  line-height: 35px;
}

.el-footer {
  background-color: #faecd8;
  height: 35px;
  text-align: center;
  line-height: 35px;
}

.el-container {
  height: 100vh;
}

.menuTitle {
  height: 35px;
  line-height: 35px;
  text-align: center;
  font-size: larger;
  color: #c45656;
}

.show {
  cursor: pointer;
}

.el-dropdown {
  float: right;
  height: 35px;
  line-height: 35px;
}

/* 修改密码弹窗样式 */
.el-dialog {
  max-width: 600px;
}

.el-form-item {
  margin-bottom: 20px;
}
</style>